package com.whmnx.chitchat.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.classic.adapter.CommonRecyclerAdapter;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.qcloud.tim.uikit.component.TitleBarLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.tencent.qcloud.tim.uikit.modules.contact.ContactItemBean;
import com.tencent.qcloud.tim.uikit.modules.contact.ContactLayout;
import com.tencent.qcloud.tim.uikit.modules.contact.ContactListView;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;
import com.whmnx.chitchat.R;
import com.whmnx.chitchat.adapter.DepAdapter;
import com.whmnx.chitchat.adapter.DynamicAdapter;
import com.whmnx.chitchat.adapter.UserAdpter;
import com.whmnx.chitchat.base.BaseFragment;
import com.whmnx.chitchat.bean.ChatMsgDatailBean;
import com.whmnx.chitchat.bean.DepartmentDean;
import com.whmnx.chitchat.bean.LoginBean;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.event.EventConstants;
import com.whmnx.chitchat.event.MessageEvent;
import com.whmnx.chitchat.http.CallBack;
import com.whmnx.chitchat.http.HttpClient;
import com.whmnx.chitchat.main.RegisterActivity;
import com.whmnx.chitchat.ui.book.ChuangFriendsActivity;
import com.whmnx.chitchat.ui.book.DepartmentActivity;
import com.whmnx.chitchat.ui.book.GroupActivity;
import com.whmnx.chitchat.ui.chat.AddGroupActivity;
import com.whmnx.chitchat.ui.chat.AddMoreActivity;
import com.whmnx.chitchat.ui.chat.ChatActivity;
import com.whmnx.chitchat.ui.my.MyActivity;
import com.whmnx.chitchat.utils.ImageUtil;
import com.whmnx.chitchat.utils.SPUtil;
import com.whmnx.chitchat.utils.UItils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.zip.Deflater;

import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author : huang
 * date   : 2020/7/21 0021 16:20
 * version: 1.0
 * @author Administrator
 */
public class BookFragment extends BaseFragment implements View.OnClickListener {

    private  ContactLayout mContactLayout;
    private  CircleImageView ivUser;
    private  ImageButton ibRight;
    private  TextView tvPeople;
    private EditText query;
    private  RecyclerView rlDep,rlUser;
    UserAdpter userAdpter;
    DepAdapter depAdapter;

    @Override
    protected int getLayoutResource() {
        return R.layout.boss_fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContactLayout = rootView.findViewById(R.id.contact_layout);
        rootView.findViewById(R.id.contact_listview);
        ivUser = rootView.findViewById(R.id.iv_user);
        ibRight = rootView.findViewById(R.id.ib_right);
        rlDep = rootView.findViewById(R.id.rl_dep);
        rlUser = rootView.findViewById(R.id.rl_user);
        tvPeople = rootView.findViewById(R.id.tv_people);
        query = rootView.findViewById(R.id.message_search);
        initView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent messageEvent) {
        if (messageEvent.getMessageKey() != null) {
            if (messageEvent.getMessageKey().equals(EventConstants.FAMILY)) {
                ImageUtil.setImage(ivUser, SPUtil.getString(Constants.HEAD_IMG));
            }
        }
    }

    private void initView() {
        rlDep.setLayoutManager(new LinearLayoutManager(getActivity()));
        rlDep.setItemAnimator(new DefaultItemAnimator());
         depAdapter = new DepAdapter(getActivity());
        rlDep.setAdapter(depAdapter);

        rlUser.setLayoutManager(new LinearLayoutManager(getActivity()));
        rlUser.setItemAnimator(new DefaultItemAnimator());
         userAdpter = new UserAdpter(getActivity());
        rlUser.setAdapter(userAdpter);

        ImageUtil.setImage(ivUser, SPUtil.getString(Constants.HEAD_IMG));
        TitleBarLayout titleBarLayout = mContactLayout.findViewById(R.id.contact_titlebar);
        titleBarLayout.setVisibility(View.GONE);
        ibRight.setOnClickListener(this);
        ivUser.setOnClickListener(this);
        Map<String, Object> params = new HashMap<>();
        params.put("OrganizeId","");
        params.put("DepartmentID","");
        HttpClient.get(getActivity(), Constants.GETDEPARTMENTLIST, params,new CallBack<DepartmentDean>() {
            @Override
            public void onSuccess(DepartmentDean result) {
                depAdapter.addAll(result.getOrganize());
                userAdpter.addAll(result.getUser());
                if (result.getUser().size() == 0){
                    tvPeople.setVisibility(View.GONE);
                }
            }
        });

        depAdapter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                startActivity(new Intent(getActivity(), DepartmentActivity.class)
                        .putExtra("OrganizeId", depAdapter.getItem(i).getOrganizeId())
                        .putExtra("name", depAdapter.getItem(i).getOrganizeName()));
            }
        });

        userAdpter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                String userId = SPUtil.getString(Constants.USERID);
                if (userId.equals(userAdpter.getItem(i).getUserId())){
                    UItils.showToastSafe("自己不能和自己聊天");
                    return;
                }
                ChatInfo chatInfo = new ChatInfo();
                chatInfo.setType(TIMConversationType.C2C);
                chatInfo.setId(userAdpter.getItem(i).getUserId());
                chatInfo.setChatName(userAdpter.getItem(i).getUserNick());
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                intent.putExtra(Constants.CHAT_INFO, chatInfo);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        query.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //点击搜索的时候隐藏软键盘
                // hideKeyboard(EditText);
                // 在这里写搜索的操作,一般都是网络请求数据
                search(v.getText().toString().trim());
              /*  if (!TextUtils.isEmpty(v.getText().toString().trim())) {
                }*/
                return true;
            }
            return false;
        });
    }

    private void search(String trim) {
        Map<String, Object> params = new HashMap<>();
        params.put("UserCon", trim);
        HttpClient.get(getActivity(), Constants.GETDEPARTMENTLIST, params, new CallBack<DepartmentDean>() {
            @Override
            public void onSuccess(DepartmentDean result) {
                depAdapter.replaceAll(result.getOrganize());
                userAdpter.replaceAll(result.getUser());
                if (result.getUser().size() == 0){
                    tvPeople.setVisibility(View.GONE);
                    UItils.showToastSafe("暂无相关信息");
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
     //   refreshData();
    }

    private void refreshData() {
        // 通讯录面板的默认 UI 和交互初始化
        mContactLayout.getContactListView().loadDataSource(ContactListView.DataSource.FRIEND_LIST);
        mContactLayout.getContactListView().setOnItemClickListener(new ContactListView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, ContactItemBean contact) {
                ChatInfo chatInfo = new ChatInfo();
                chatInfo.setType(contact.isGroup() ? TIMConversationType.Group : TIMConversationType.C2C);
                chatInfo.setId(contact.getId());
                chatInfo.setChatName(contact.getNickname());
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                intent.putExtra(Constants.CHAT_INFO, chatInfo);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ib_right) {
            UItils.startActivity(AddMoreActivity.class);
        } else {
            UItils.startActivity(MyActivity.class);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.ll_friend, R.id.ll_group, R.id.ll_chuang})
    public void onViewClicked(View view) {
        //AddGroupActivity
        switch (view.getId()) {
            case R.id.ll_friend:
                startActivity(new Intent(getActivity(),AddGroupActivity.class).putExtra("type",1));
             //   UItils.startActivity(AddGroupActivity.class);
                break;
            case R.id.ll_group:
                UItils.startActivity(GroupActivity.class);
                break;
            case R.id.ll_chuang:
                UItils.startActivity(ChuangFriendsActivity.class);
                break;
            default:
        }
    }
}
